<template>

  <div class="app-container">
    <!--普通用户界面  start-->
    <div v-if="roleType === '2'">
      <in-body>
        <div class="buttonTop" style="display: flex">
          <div style="margin-left: 15px">
            <el-button type="primary" plain @click="createRepair">+点击报修</el-button>
          </div>
        </div>
      </in-body>
      <div style="display: flex;flex-wrap: wrap;margin-left: 245px">
        <div v-for="item in repairList" :key="item.id" style="margin-left: 10px;margin-bottom: 10px">
          <el-card class="box-card" style="width: 380px;height: 120px;margin-left: 10px;margin-bottom: 10px">
            <div slot="header" class="clearfix">
              <span>{{ item.title | ellipsis }}</span>
              <el-tag style="margin-left: 10px" :type="handlerRepairTagType(item)">{{ handlerRepairTagTitle(item) }}</el-tag>
              <i class="el-icon-delete" style="float: right;margin-top: 2px;margin-left: 10px" />
              <el-button style="float: right; padding: 3px 0" type="text" @click="repairDetail(item.id)">查看详情</el-button>
            </div>
            <div class="text item">
              {{ item.content }}
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <!--普通用户界面  start-->

    <!--维修员工界面  start-->
    <div v-if="roleType === '3'" style="display: flex">
      <in-body>
        <div class="buttonTop" style="display: flex">
          <el-radio-group v-model="radioModel" type="vertical" @change="radioChange">
            <div>
              <el-radio-button label="我报修的" />
            </div>
            <div>
              <el-radio-button label="我维修的" />
            </div>
          </el-radio-group>
          <div style="margin-left: 15px">
            <div>
              <el-select v-model="searchData.status" style="width: 90px;margin-top: 2px" size="small" clearable placeholder="状态" @change="seleceChange">
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div v-show="radioModel === '我报修的'" style="margin-top: 12px">
              <el-button type="primary" size="small" plain @click="createRepair">+点击报修</el-button>
            </div>
          </div>
        </div>
      </in-body>
      <div style="display: flex;flex-wrap: wrap;margin-left: 245px">
        <div v-for="item in repairList" :key="item.id" style="margin-left: 10px;margin-bottom: 10px">
          <el-card class="box-card" style="width: 380px;height: 120px;margin-left: 10px;margin-bottom: 10px">
            <div slot="header" class="clearfix">
              <span>{{ item.title | ellipsis }}</span>
              <el-tag style="margin-left: 10px" :type="handlerRepairTagType(item)">{{ handlerRepairTagTitle(item) }}</el-tag>
              <i class="el-icon-delete" style="float: right;margin-top: 2px;margin-left: 10px" />
              <el-button style="float: right; padding: 3px 0" type="text" @click="radioModel === '我报修的' ? repairDetail(item.id) : viewDetail(item)">查看详情</el-button>
            </div>
            <div class="text item">
              {{ item.content }}
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <!--维修员工界面  start-->

    <!--管理员界面 start-->
    <div v-if="roleType === '1'">
      <!--搜索栏start-->
      <div class="searchMultiple" style="width: 100%">
        <el-select v-model="searchData.buildInfo" clearable filterable placeholder="小区名称" @change="managerSelectChange">
          <el-option
            v-for="item in xiaoquList"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
        <el-select v-model="searchData.status" style="margin-left: 10px" clearable filterable placeholder="维修单状态" @change="managerSelectChange">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button style="margin-left: 1%" type="primary" round icon="el-icon-close" @click="clearContent()">清空</el-button>
      </div>
      <!--搜索栏end-->

      <!--表格区域start-->
      <div style="margin-top: 20px">
        <!--表格start-->
        <el-table
          :data="repairData"
          style="width: 100%"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="住房信息">
                  <span>{{ props.row.buildInfo }}</span>
                </el-form-item>
                <el-form-item label="标题">
                  <span>{{ props.row.title }}</span>
                </el-form-item>
                <el-form-item label="图片描述">
                  <template>
                    <el-image style="width: 200px;height: 200px" :src="props.row.picture" />
                  </template>
                </el-form-item>
                <el-form-item label="状态">
                  <span>{{ handlerRepairTagTitle(props.row) }}</span>
                </el-form-item>
                <el-form-item label="详细说明">
                  <span>{{ props.row.content }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            label="楼房信息"
            prop="buildInfo"
          />
          <el-table-column
            label="标题"
            prop="title"
          />
          <el-table-column
            label="详细说明"
            prop="content"
          />
          <el-table-column
            label="状态"
            prop="status"
          >
            <template slot-scope="scope">
              <el-tag :type="handlerRepairTagType(scope.row)">{{ handlerRepairTagTitle(scope.row) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="处理人(手机号)"
            prop="handlerName"
          />
          <el-table-column
            label="操作"
          >
            <template slot-scope="props">
              <el-dropdown>
                <span class="el-dropdown-link">
                  分配维修单<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="item in repairWorkerList" :key="item.id" @click.native="fenpeiRepairWorker(props.row.id, item.id)">{{ item.name }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button style="margin-left: 10px" type="danger" plain size="mini" @click="bohui(props.row.id)">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--表格end-->

        <!--分页插件start-->
        <el-pagination
          style="margin-top: 1%;display: flex;justify-content: right"
          background
          layout="prev, pager, next"
          :page-size="size"
          :total="total"
          :current-page.sync="searchData.pageNumber"
          @current-change="currentChange"
        />
        <!--分页插件end-->
      </div>
      <!--表格区域end-->

    </div>
    <!--管理员界面 end-->

    <!--新增弹出框  start-->
    <el-dialog title="创建维修单" :visible.sync="dialogFormVisible">
      <el-form ref="repairForm" :model="repairForm" :rules="rules" label-width="100px">
        <el-form-item label="住房信息" prop="buildInfo">
          <el-select v-model="repairForm.buildInfo" placeholder="请选择">
            <el-option
              v-for="item in userBuilds"
              :key="item.id"
              :label="item.xiaoquName + item.buildNo + '-' + item.unitNo + '-' + item.houseNo"
              :value="item.xiaoquName + item.buildNo + '-' + item.unitNo + '-' + item.houseNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="repairForm.title" />
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <el-upload
            class="avatar-uploader"
            action="http://39.106.32.84:8080/PMSystem/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="repairForm.picture" :src="repairForm.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="详细说明">
          <el-input v-model="repairForm.content" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSave">确 定</el-button>
      </div>
    </el-dialog>
    <!--新增弹出框  end-->

    <!--编辑框 start-->
    <el-dialog title="处理维修单" :visible.sync="editFormVisible">
      <el-form :model="repairForm" label-width="100px">
        <el-form-item label="住房信息">
          {{ repairForm.buildInfo }}
        </el-form-item>
        <el-form-item label="标题">
          {{ repairForm.title }}
        </el-form-item>
        <el-form-item label="图片">
          <img style="width: 100px;height: 100px" :src="repairForm.picture">
        </el-form-item>
        <el-form-item label="详细说明">
          {{ repairForm.content }}
        </el-form-item>
        <el-form-item label="是否解决">
          <el-select v-if="repairForm.status === 2" v-model="repairForm.success" placeholder="请选择">
            <el-option
              v-for="item in trueAndFalse"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span v-if="repairForm.status === 3">{{ repairForm.success ? '是' : '否' }}</span>
        </el-form-item>
        <el-form-item v-if="repairForm.success === false && repairForm.status === 2" label="原因">
          <el-input
            v-model="repairForm.result"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item v-if="repairForm.success === false && repairForm.status === 3" label="原因">
          {{ repairForm.result }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSaveClick">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑框 start-->
  </div>

</template>

<script>
import { getToken } from '@/utils/auth'
import { fenpeiWorker, getWorks } from '@/api/houseHold'
import { handleRepair, getRepairOfWorks, getRepairList, addRepair, getCurrentUserBuilds, getAllList, bohuiRepair } from '@/api/repair'
import { getList } from '@/api/apartment'

export default {
  filters: { // 当文字过长时过滤器
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 10) {
        return value.slice(0, 10) + '...'
      }
      return value
    }
  },
  data() {
    return {
      radioModel: '我报修的',
      total: 0, // 分页插件总记录数
      size: 0, // 分页插件每页显示个数
      xiaoquName: '', // 小区名称
      roleType: '', // 角色类型
      tagType: 'warning',
      repairTag: '', // 维修单状态
      userBuilds: [], // 当前用户的住房列表
      repairList: [], // 维修单列表
      repairWorkerList: [], // 维修工人列表
      statusList: [{
        value: 1,
        label: '审核中'
      }, {
        value: 2,
        label: '处理中'
      }, {
        value: 3,
        label: '已处理'
      }],
      xiaoquList: [], // 小区列表
      uploadHeaders: { Authorization: getToken() }, // 文件上传请求头
      dialogFormVisible: false, // 是否显示表单对话框
      editFormVisible: false, // 编辑维修单对话框
      repairForm: { // 维修单表单
        buildInfo: '', // 楼房信息
        title: '', // 标题
        picture: '', // 图片
        content: '', // 详细描述
        result: '', // 结果（原因）
        success: '' // 是否成功
      },
      searchData: { // 查询参数
        buildInfo: '', // 楼房信息
        status: '', // 维修单状态
        pageNumber: 1, // 接口默认的页数
        pageSize: 5 // 接口默认的每页大小
      },
      rules: { // 校验规则
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        picture: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        buildInfo: [
          { required: true, message: '请填写住房信息', trigger: 'blur' }
        ]
      },
      repairData: [], // 维修单表格数据
      trueAndFalse: [{ // 是or否
        value: true,
        label: '是'
      }, {
        value: false,
        label: '否'
      }]
    }
  },
  created() {
    this.roleType = window.localStorage.getItem('roleType')

    if (this.roleType === '2' || this.roleType === '3') { // 如果是普通用户
      this.getRepairs() // 获取用户所有维修单
      this.getBuilds() // 获取用户所有住房信息
    }

    if (this.roleType === '1') { // 如果是管理员
      this.finalSelect() // 获取所有的维修单列表
      this.getRepairWorks() // 获取所有维修工人
      this.getXiaoQuList() // 获取小区列表
    }
  },
  methods: {
    getRepairs() {
      getRepairList({ status: this.searchData.status }).then(res => {
        this.repairList = res.data
      })
    },
    repairDetail(id) { // 普通用户点击进入详情
      this.$router.push({
        path: '/repair/repairDetail',
        query: {
          repairId: id
        }
      })
    },
    createRepair() { // 点击创建维修单
      this.repairForm.picture = ''
      this.repairForm.buildInfo = ''
      this.repairForm.content = ''
      this.repairForm.title = ''
      this.repairForm.id = ''
      this.repairForm.status = ''
      this.repairForm.success = ''
      this.repairForm.result = ''
      this.dialogFormVisible = true
    },
    handleAvatarSuccess(res) { // 上传成功函数
      this.imageUrl = res.data
      this.repairForm.picture = res.data
    },
    beforeAvatarUpload(file) { // 上传之前
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    clickSave() {
      this.$refs['repairForm'].validate((valid) => {
        if (valid) {
          addRepair(this.repairForm).then(res => {
            this.dialogFormVisible = false
            if (res.code === 20000) {
              this.getRepairs()
              this.$message.success('添加成功！')
            } else {
              this.$message.error('添加失败！')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getBuilds() { // 获取当前登录普通用户的住房列表
      getCurrentUserBuilds().then(res => {
        this.userBuilds = res.data
      })
    },
    handlerRepairTagType(item) {
      if (item.success === false) {
        return 'danger'
      } else {
        if (item.status === 1) {
          return ''
        }
        if (item.status === 2) {
          return 'warning'
        }
        if (item.status === 3) {
          return 'success'
        }
      }
    },
    handlerRepairTagTitle(item) { // 状态标签标题处理函数
      if (item.success === false) {
        if (item.status === 2) {
          return '被驳回'
        }
        if (item.status === 3) {
          return '未解决'
        }
      } else {
        if (item.status === 1) {
          return '审核中'
        }
        if (item.status === 2) {
          return '处理中'
        }
        if (item.status === 3) {
          return '已处理'
        }
      }
    },
    xiaoquNameInputChange(value) { // 小区名称输入框chang函数
      if (value === '' || value == null) {
        this.xiaoquName = null
      }
    },
    clearContent() { // 清空输入框方法
      this.searchData.buildInfo = null
      this.searchData.status = null
      this.searchData.name = null
      this.searchData.number = null
      this.searchData.startTime = null
      this.searchData.endTime = null
      this.createTime = null
      this.searchData.pageNumber = 1
      this.finalSelect()
    },
    currentChange(val) { // 点击分页栏方法（管理员端）
      this.searchData.pageNumber = val
      this.finalSelect()
    },
    finalSelect() { // 封装后的查询维修单列表方法（管理员端方法）
      getAllList(this.searchData).then(res => {
        if (res.data.records) {
          this.repairData = res.data.records
          this.total = res.data.total
          this.size = res.data.size
          console.log(res.data)
        } else {
          this.repairData = res.data
        }
      })
    },
    getRepairWorks() { // 获取维修人员列表
      getWorks().then(res => {
        this.repairWorkerList = res.data
      })
    },
    fenpeiRepairWorker(repairId, userId) { // 给维修单分配维修人员
      fenpeiWorker(repairId, userId).then(res => {
        this.$message.success('分配成功')
        this.finalSelect()
      })
    },
    bohui(id) { // 驳回维修单申请
      this.$confirm('确定要驳回该申请嘛?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        bohuiRepair(id).then(res => {
          if (res.data.code === 20000) {
            this.finalSelect()
            this.$message.success('驳回成功')
          } else {
            this.$message.error('驳回失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消驳回'
        })
      })
    },
    getWorkerRepairs() { // 获取维修员工需要处理的维修单
      getRepairOfWorks({ status: this.searchData.status }).then(res => {
        this.repairList = res.data
      })
    },
    viewDetail(item) { // 维修人员点击查看详情
      this.editFormVisible = true
      this.repairForm.picture = item.picture
      this.repairForm.buildInfo = item.buildInfo
      this.repairForm.content = item.content
      this.repairForm.title = item.title
      this.repairForm.id = item.id
      this.repairForm.status = item.status
      this.repairForm.success = item.success
      this.repairForm.result = item.result
    },
    editSaveClick() { // 维修人员点击保存修改
      handleRepair(this.repairForm.id, this.repairForm).then(res => {
        if (res.code === 20000) {
          this.editFormVisible = false
          this.getWorkerRepairs()
          this.$message.success('处理成功！')
        }
      })
    },
    radioChange() {
      console.log(this.radioModel)
      this.searchData.status = null
      if (this.radioModel === '我报修的') {
        this.getRepairs() // 获取用户所有维修单
        this.getBuilds() // 获取用户住房列表
      }
      if (this.radioModel === '我维修的') {
        this.getWorkerRepairs() // 获取该维修人员负责的所有维修单
      }
    },
    seleceChange() { // 普通用户选择变化函数
      if (this.radioModel === '我报修的') {
        this.getRepairs()
      } else {
        this.getWorkerRepairs()
      }
    },
    managerSelectChange() { // 管理员选择变化函数
      if (this.roleType === '1') {
        this.finalSelect()
      }
    },
    getXiaoQuList() { // 获取小区列表
      getList().then(res => {
        this.xiaoquList = res.data
      })
    }
  }
}
</script>

<style lang="scss">
html,body {height:100%;overflow:auto;margin: 0;}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.buttonTop{
  position: fixed;
  top: 72px;
  left: 50px;
  .el-radio{
    display: block;
    margin:10px 0;
  }
}

.el-radio-button:first-child:last-child .el-radio-button__inner {
  border-radius: 0;
}
</style>
